﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace QaaSimulation.QSim
{
    class QSpaceControl : Control
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetKeyboardState(byte[] lpKeyState);

        public QSpaceShip m_PlayerShip;
        
        public Timer timer;
        public QSpaceControl()
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
            m_PlayerShip = new QSpaceShip();
            timer = new Timer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = 40;
        }
        delegate void HandleTickCallback();

        void timer_Tick(object sender, EventArgs e)
        {
            HandleTick();
        }

        private void HandleTick()
        {
            if (this.InvokeRequired)
            {
                HandleTickCallback d = new HandleTickCallback(HandleTick);
                this.Invoke(d);
            }
            else
            {
                byte[] array = new byte[256];
                GetKeyboardState(array);
                m_PlayerShip.HandleInput(array);
                m_PlayerShip.Compute(timer.Interval / 1000f);
                Refresh();
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (m_PlayerShip != null)
                m_PlayerShip.Paint(e.Graphics);
        }

        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            base.OnMouseDoubleClick(e);

        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            this.Focus();
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            
        }
    }
}
